package com.linkage.seapeak.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProTalkDetailActivity;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.fragment.MsgFragment;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.seapeak.activity.chat.ChatDetailActivity;
import com.linkage.seapeak.activity.message.GoToPageLoadingActivity;
import com.linkage.seapeak.adapter.ConversationAdapter;
import com.linkage.seapeak.net.ResultCallBack;
import com.linkage.seapeak.pojo.MessageBundle;
import com.linkage.seapeak.pojo.MessageItem;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.content.Context.INPUT_METHOD_SERVICE;

public class ConversationNoticeFragment extends BaseNoticeFragment implements AYSwipeRecyclerView.OnRefreshLoadListener {

    Boolean initData = false;
    ArrayList<MessageItem> mDataList;
    private LinearLayout topSlider;
    private EditText pro_spinner;
    private AYSwipeRecyclerView recycler;
    private ConversationAdapter adapter;

    private List<MyProInfo> proList;
    private int currentSelect = 0;

    /**
     * 监听请求状态
     */
    private Subscription subscription;

    public void setProList(List<MyProInfo> proList) {
        this.proList = proList;
        /**
         * view 表示要附着的控件, menuList 表示要展示的菜单列表,
         * DetailActivity 表示当前页面的 Activity
         */
        PopupMenu popupMenu = new PopupMenu(getActivity(), pro_spinner);
        android.view.Menu menu_more = popupMenu.getMenu();
        int size = proList.size();
        for (int i = 0; i < size; i++) {
            menu_more.add(android.view.Menu.NONE, android.view.Menu.FIRST + i, i, proList.get(i).getProjectName());
        }
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                currentSelect = item.getOrder();
                MyProInfo info =  proList.get(currentSelect);
                pro_spinner.setText(info.getProjectName());
                page=1;
                getData();
                return true;
            }
        });
        popupMenu.show();
    }

    public static ConversationNoticeFragment newInstance() {
        return new ConversationNoticeFragment();
    }

    public ConversationNoticeFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_conversation_list, container, false);
        topSlider = (LinearLayout) view.findViewById(R.id.top_slider);
        pro_spinner = (EditText) view.findViewById(R.id.pro_spinner);
        recycler = (AYSwipeRecyclerView) view.findViewById(R.id.recycler);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData = true;
        mDataList = new ArrayList<>();
        init();
    }

    private void init() {
        recycler.setOnRefreshLoadLister(this);
        adapter = new ConversationAdapter(getActivity(), 1, mDataList);
        recycler.setAdapter(adapter);
        recycler.setMode(AYSwipeRecyclerView.SwipeType.BOTH);
        View emptyView = View.inflate(getActivity(), R.layout.recycle_empty_notice, null);
        ImageView empty_image = emptyView.findViewById(R.id.empty_image);
        TextView empty_text = emptyView.findViewById(R.id.empty_text);

        empty_image.setImageResource(R.drawable.icon_empty_notice);
        empty_text.setText("暂无通知");

        pro_spinner.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                    String key = pro_spinner.getText().toString().trim();
                    hideInput();
//                    if (!TextUtils.isEmpty(key)) {
                        if (subscription != null && !subscription.isUnsubscribed())
                            subscription.unsubscribe();
                        getMyProList(key);
//                    } else {
//                        if(proList!=null)
//                            proList.clear();
//                        getData();
//                    }
                    return true;
//                }

//                return false;
            }
        });


        pro_spinner.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
//                String key = pro_spinner.getText().toString().trim();
//                hideInput();
//                if (!TextUtils.isEmpty(key)) {
//                    if (subscription != null && !subscription.isUnsubscribed())
//                        subscription.unsubscribe();
//                    getMyProList(key);
//                } else {
//                    if(proList!=null)
//                    proList.clear();
//                    getData();
//                }
            }
        });

        recycler.setEmptyView(emptyView);
        recycler.setOnItemLongClickListener(new BaseRecyclerAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(View v, int position)
            {
                return true;
            }
        });

        recycler.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, final int position, RecyclerView.ViewHolder viewHolder) {

                MessageItem item = mDataList.get(position);
                EventBus.getDefault().post(new MsgFragment.UnreadMsg());
                if (v.getId() == R.id.et_item_bgaswipe_read) {
                    showProgress();
                    readone(item.getId(), new ResultCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            hideProgress();
//                            getData();
                            loadFirst();
                        }

                        @Override
                        public void onFailed(String msg) {
                            hideProgress();
                            showToast(msg);
                        }
                    });
                } else if (v.getId() == R.id.tv_item_bgaswipe_delete) {
                    showProgress();
                    deleteMsg(item.getId(), new ResultCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            hideProgress();
                            recycler.removeView(v);
//                            getData();
                            loadFirst();
                        }

                        @Override
                        public void onFailed(String msg) {
                            hideProgress();
                            showToast(msg);
                        }
                    });
                } else {
                    readone(item.getId(), new ResultCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            hideProgress();
                            GoToPageLoadingActivity.start(getActivity(), item.getId(), 0);
                        }

                        @Override
                        public void onFailed(String msg) {
                            hideProgress();
                            showToast(msg);
                        }
                    });
                }
            }
        });
    }

    /**
     * 检查数据发送广播
     */
    public void checkItems() {
        page = 1;
        getData();
        pro_spinner.setText("");
//        if (mDataList != null)
//            EventBus.getDefault().post(new MainActivity.ShowHideClearAll(mDataList.size() > 0));
    }

    int page = 1;


    /**
     * 获取数据
     */
    String proId = "";
    private void getData() {
        if (proList != null && proList.size() > 0)
            proId = proList.get(currentSelect).getId();
        else
            proId = "";
        getMsgList(page, 10, 1, proId, new ResultCallBack<MessageBundle>() {
            @Override
            public void onSuccess(MessageBundle result) {
                if(mDataList ==null)
                {
                    return;
                }
                if (page == 1)
                {
                    mDataList.clear();
                }

                page++;
                mDataList.addAll(result.getMessageItems());
                EventBus.getDefault().post(new MainActivity.ShowHideClearAll(mDataList.size() > 0));
                recycler.onFinishRequest(false, result.getCount() > mDataList.size());
                topSlider.setVisibility(mDataList.size() == 0 ? (TextUtils.isEmpty(proId) ? View.GONE : View.VISIBLE) : View.VISIBLE);
            }

            @Override
            public void onFailed(String msg) {
                if(mDataList !=null) {
                    mDataList.clear();
                    recycler.onFinishRequest(true, false);
                    topSlider.setVisibility(TextUtils.isEmpty(proId) ? View.GONE : View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void loadFirst() {
        page = 1;
        getData();
    }

    @Override
    public void loadNext() {
        getData();
    }

    /**
     * 获取项目，展示弹窗
     * @param key
     */
    public void getMyProList(String key) {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        subscription = Network.getAPIService()
                .getMyProList(userToken, key, 1, 200)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        try {
                            int code = json.get("code").getAsInt();
                            if (code == 0) {
                                JsonObject data = json.getAsJsonObject("data");
                                JsonArray arr = data.getAsJsonArray("list");
                                List<MyProInfo> list = MyProInfo.parse(arr);
//                            添加一个空的组
                                setProList(list);
                            }
                        }catch (Exception ex) {
                            ex.printStackTrace();;
                        }

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }


    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
        View v = getActivity().getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
